$(function () {

    // 定义的初始化变量
    var allPage, page, searchKey, company, provinceId, status, type;

   categoryList="";

    function getCategreadList() {
        $.ajax({
            async: false,
            cache: false,
            headers: {"Accept-CMS-Token": token},
            url: finddictlist,
            type: 'get',
            data: {
                type: 8
            },
            dataType: 'json',
            success: function (res) {
                //console.log(res)
                categoryList = res;
                //console.log(categoryList)

            },
            error: function (error) {
                layer.msg("获取失败！");
            }
        })
        //console.log(categoryList)
    }
    getCategreadList();

    // 获取省列表    产地
    function getProvince() {
        $.ajax({
            type: 'post',
            headers: {"Accept-CMS-Token": token},
            url: provincelist,
            dataType: 'json',
            data: {},
            success: function (data) {
                if (data.resultCode == 200) {
                    var value = data.value;
                    var str = '';
                    for (var i = 0; i < value.length; i++) {
                        str += '<option value="' + value[i].id + '">' + value[i].fullName + '</option>'

                    }
                    $('.province').append(str);
                    console.log('获取省接口调通!!!!');
                }
                else if (data.resultCode == 515) {
                    reLogin();
                }
            },
            error: function () {
                console.log('获取省接口请求失败');
            },
        });
    };
    getProvince();

    //获取供应商(厂商)列表       单独的接口.....
    function setSupplier() {
        $.ajax({
            type: 'post',
            headers: {"Accept-CMS-Token": token},
            url: findcompany,
            dataType: 'json',
            data: {
                type: 1
            },
            success: function (data) {
                if (data.resultCode == 200) {
                    var standard = data.value;
                    var len = standard.length;
                    var str = '';
                    for (var i = 0; i < len; i++) {
                        str += '<option value="">' + standard[i] + '</option>';
                    }
                    ;
                    $('.supplier').append(str);
                    console.log('查询所有厂商列表接口调通!!!!')
                }
                else if (data.resultCode == 515) {
                    reLogin();
                }
            },
            error: function () {
                console.log('查询所有厂商列表接口请求失败')
            },
        });
    };
    setSupplier();

    //获取品类
    function getCategoryList() {
        $.ajax({
            async: false,
            cache: false,
            headers: {"Accept-CMS-Token": token},
            url: finddictlist,
            type: 'get',
            data: {
                type: 8
            },
            dataType: 'json',
            success: function (res) {
                var option = '<option value="">全部</option>';
                var value = res.value;
                for (var i = 0; i < value.length; i++) {
                    option = option + "<option value=" + value[i].description + ">" + value[i].name + "</option>";
                }
                $(".category").append(option);
                $('div.intelligence').show();
            },
            error: function (error) {
                layer.msg("获取失败！");
            }
        });
    };

    getCategoryList();

    // 页面初始化....商品列表
    page = getCommodityList('', 1, '', '', '', '', '');
    getPage(page);


    //页面初始化....商品列表...页面中有多个地方用到了这个函数....
    function getCommodityList(company, page, provinceId, categoryId, searchKey, status, type) {

        $.ajax({
            async: false,
            cache: false,
            type: 'post',
            headers: {"Accept-CMS-Token": token},
            url: shopcommonditylist,
            dataType: 'json',
            data: {
                company: company,
                page: page,
                provinceId: provinceId,
                categoryId: categoryId,
                searchKey: searchKey,
                size: 10,
                status: status,
                type: type
            },
            success: successFn,
            error: function () {
                console.log('查看商品列表接口请求失败');
            },
        });
        return allPage;

    };

    // 将加载商品列表的ajax请求成功之后要执行的函数进行封装....
    function successFn(data) {


        if (data.resultCode == 200) {//搜索的数据显示到前端的页面当中....
            var value = data.value;
            allPage = data.count;
            if (value.length > 0) {
                //清空表格
                clearTable();
                //先生成表格,表格当中正常要显示的内容.......
                for (var i = 0; i < value.length; i++) {
                    $('.shangpin_admin tbody').append('<tr intelligenceId="' + value[i].id + '"></tr>');//属性

                    $('.shangpin_admin tbody tr').eq(i).append('<td>' + (i + 1) + '</td>');//序号

                    $('.shangpin_admin tbody tr').eq(i).append('<td>' + value[i].name + '</td>');//名称

                    $('.shangpin_admin tbody tr').eq(i).append('<td style="padding: 5px;"><img src="' + address + value[i].coverUrl + '" alt="封面图片" width="100" height="60"></td>');//图片

                    $('.shangpin_admin tbody tr').eq(i).append('<td>' + changeCategoryChinese(value[i].type) + '</td>');//品类

                    $('.shangpin_admin tbody tr').eq(i).append('<td>' + value[i].price + '</td>');//价格/元

                    $('.shangpin_admin tbody tr').eq(i).append('<td>' + changeZero(value[i].totalNum) + '</td>');//库存/个

                    $('.shangpin_admin tbody tr').eq(i).append('<td>' + changeZero(value[i].totalSalesNum) + '</td>');//销量

                    $('.shangpin_admin tbody tr').eq(i).append('<td>' + changeStatus(value[i].status) + '</td>');//状态

                    $('.shangpin_admin tbody tr').eq(i).append('<td>' + cutWord(value[i].info) + '</td>');//简介

                    $('.shangpin_admin tbody tr').eq(i).append('<td>' + getMoth(value[i].statusCreateTime) + '</td>');//上架时间

                    $('.shangpin_admin tbody tr').eq(i).append('<td>' + (value[i].areaProvinceName) + '-' + (value[i].areaCityName) + '</td>');//产地

                    $('.shangpin_admin tbody tr').eq(i).append('<td>' + cutWord(value[i].company) + '</td>');//供应商

                    //向最后一个表格的操作项添加东西
                    //if (value[i].type == 1) {
                        // return '智能硬件';

                        $('.shangpin_admin tbody tr').eq(i).append('<td><a href="#" class="ed ed_intelligence">编辑</a><a href="#" class="ed look_intelligence">查看</a></td>');


                    //} else if (value[i].type == 2) {
                    //    // return '中药'
                    //
                    //    $('.shangpin_admin tbody tr').eq(i).append('<td><a href="#" class="ed ed_zhongYao">编辑</a><a href="#" class="ed look_zhongYao">查看</a></td>');
                    //
                    //}
                    //;


                }
                ;
                //根据后台返回来的状态,,,去为表格的操作添加上架或者下架的按钮
                for (var j = 0; j < value.length; j++) {
                    if (value[j].status == 0 || value[j].status == 1 || value[j].status == 2) {//当是商品的状态是正常或者售罄的时候,,商品是处于上架状态,,那么只能对这个商品进行下架的操作,,所以操作栏显示下架..
                        $('.shangpin_admin tbody tr').eq(j).children('td').eq(12).append('<a class="ed shelf" href="#">下架</a>');
                    }
                    else if (value[j].status == 3) {
                        $('.shangpin_admin tbody tr').eq(j).children('td').eq(12).append('<a class="ed shelf" href="#">上架</a>');
                    }
                    ;
                }
                ;

            }
            ;
            // console.log(value[0].status)
            console.log('查看商品列表接口调通!!!!');
        }
        else if (data.resultCode == 500) {//要搜索的东西不存在...
            clearTable();
            $('.shangpin_admin').append('<tr><td></td><td></td><td></td><td></td><td>您搜索的内容不存在</td><td></td><td></td><td></td><td></td><td></td><td style="width: 17.5%;"></td><td></td><td></td></tr>');
            hintUser();
            allPage = 1;
        }
        else if (data.resultCode == 515) {
            reLogin();
        }
    };


    //分页插件的封装,方便多次调用
    function getPage(allPage) {
        $('.M-box2').pagination({
            pageCount: allPage,
            jump: true,
            coping: true,
            homePage: '首页',
            endPage: '末页',
            prevContent: '上页',
            nextContent: '下页',
            callback: function (api) {//当点击页面当中分页的时候,会出发这个callback函数;;;;
                var page = api.getCurrent() + "";//得到的是要跳转到的那一页的页码;
                searchKey = $('input[name = searchKey]').val();
                status = $('.status option:selected').val();
                provinceId = $('.province option:selected').val();
                company = $('.supplier option:selected').html();
                type = $('.category option:selected').val();

                if (company == '全部') {
                    company = '';
                }
                ;
                getCommodityList(company, page, provinceId, '', searchKey, status, type);
            }
        });
    };

    //清空表格当中的数据,并且追加表头
    function clearTable() {
        $('.shangpin_admin').html('');
        $('.shangpin_admin').append('<thead><tr><th>序号</th><th>名称</th><th>图片</th><th>品类</th><th>价格/元</th><th>库存/个</th><th>销量</th><th>状态</th><th>简介</th><th>上架时间</th><th>产地</th><th>供应商</th><th style="width: 17.5%;">操作</th></tr></thead><tbody></tbody>');
        // $('.shangpin_admin tr').eq(0).append('');
    };

    //对表格当中的的操作加事件,,,就是点击上架,,点击下架
    $(document).on('click', '.shelf', function () {

        var shelfCont = $(this).html();
        var intelligenceId = $(this).parent('td').parent('tr').attr('intelligenceid');

        if (shelfCont == '下架') {
            $(this).html('上架');
            $(this).parent('td').parent('tr').children('td').eq(5).html('下架');
            AjaxChangeShelf(intelligenceId, restoreCount(shelfCont));
        }
        else if (shelfCont == '上架') {
            $(this).html('下架');
            $(this).parent('td').parent('tr').children('td').eq(5).html('正常');
            AjaxChangeShelf(intelligenceId, restoreCount(shelfCont));
        }
        ;

    });


    // 将商品的上架或者下架的状态跟后天做交互,,,当点击操作中的上架或者下架时要用到这个函数...
    function AjaxChangeShelf(commondityId, status) {
        $.ajax({
            type: 'post',
            headers: {"Accept-CMS-Token": token},
            url: shopcommondityupordown,
            dataType: 'json',
            data: {
                commondityId: commondityId,
                status: status
            },
            success: function (data) {
                if (data.resultCode == 200) {
                    console.log(data)
                    console.log('商品上架或者下架接口调通!!!!')
                }
                else if (data.resultCode == 515) {
                    reLogin();
                }
            },
            error: function () {
                console.log('商品上架或者下架接口请求失败')
            },
        });
    };

    //将操作中的上架或者下架转换成0或者1,,,方便跟后天做交互...
    function restoreCount(para) {
        if (para == '下架') {
            return 0;
        }
        else if (para == '上架') {
            return 1;
        }
    };

    // 在处理列表的时候,,将数据为null的数据变成0;
    function changeZero(para) {
        if (para == null) {
            return 0;
        }
        else {
            return para;
        }
    };

    //在处理列表的时候,,,将状态变成正常或者售罄...这两个
    function changeStatus(para) {
        if (para == 1 || para == 0) {
            return '正常';
        }
        else if (para == 2) {
            return '售罄';
        }
        else if (para == 3) {
            return '下架';
        }
    };

    //在处理列表的时候,,,将商品的简介中的文字截取下来...只留下6个文字...
    function cutWord(para) {
        if ((para == '') || (para == null)) {
            return '';
        }
        else {
            return para.substring(0, 6) + '......';
        }
    };

    //在处理列表的时候,,,将毫秒时间格式化为yyyy-MM-dd;
    function getMoth(str) {
        var oDate = new Date(str),
            oYear = oDate.getFullYear(),
            oMonth = oDate.getMonth() + 1,
            oDay = oDate.getDate(),
            oTime = getzf(oYear) + '-' + getzf(oMonth) + '-' + getzf(oDay);//最后拼接时间
        return oTime;
    };

    //将日期补0操作
    function getzf(num) {
        if (parseInt(num) < 10) {
            num = '0' + num;
        }
        return num;
    };




    // 处理品类...将品类后台的数字处理成文字
    function changeCategoryChinese(para) {

        //console.log(categoryList)

        var value = categoryList.value;
        for (var i = 0; i < value.length; i++) {
            //console.log(para==value[i].description)
            if (para == value[i].description) {
                console.log(value[i].name)
                return value[i].name;
            }
        }


        //
        //if(para == 1){
        //    return '智能硬件';
        //
        //}else if(para == 2){
        //    return '中药'
        //
        //}else if(para == 3){
        //    return '其他';
        //
        //}

    };


    //分页插件的封装,方便多次调用
    function getPage(allPage) {
        $('.M-box2').pagination({
            pageCount: allPage,
            jump: true,
            coping: true,
            homePage: '首页',
            endPage: '末页',
            prevContent: '上页',
            nextContent: '下页',
            callback: function (api) {//当点击页面当中分页的时候,会出发这个callback函数;;;;
                var page = api.getCurrent() + "";//得到的是要跳转到的那一页的页码;
                searchKey = $('input[name = searchKey]').val();
                status = $('.status option:selected').val();
                provinceId = $('.province option:selected').val();
                company = $('.supplier option:selected').html();
                type = $('.category option:selected').val();

                if (company == '全部') {
                    company = '';
                }
                ;
                getCommodityList(company, page, provinceId, '', searchKey, status, type);
            }
        });
    };

    //页面的搜索功能   已经做好
    $('.search_shangpin').click(function () {
        searchKey = $('input[name = searchKey]').val();
        status = $('.status option:selected').val();
        provinceId = $('.province option:selected').val();
        company = $('.supplier option:selected').html();
        type = $('.category option:selected').val();

        if (company == '全部') {
            company = '';
        }
        ;
        // getCommodityList( company,page,provinceId,categoryId,searchKey,status,type )
        page = getCommodityList(company, 1, provinceId, '', searchKey, status, type);
        getPage(page);
        // $('input[name = searchKey]').val('');
    });

    //当输入文本框中时,,,按下enter键,,,发起搜索,,,
    $(document).keydown(function (event) {
        var ev = ev || event;

        if (ev.keyCode == 13) {
            searchKey = $('input[name = searchKey]').val();
            status = $('.status option:selected').val();
            provinceId = $('.province option:selected').val();
            company = $('.supplier option:selected').html();
            type = $('.category option:selected').val();

            if (company == '全部') {
                company = '';
            }
            ;
            page = getCommodityList(company, 1, provinceId, '', searchKey, status, type);
            getPage(page);
            // $('input[name = searchKey]').val('');
        }
        ;

    });

    // 每一个下拉菜单发生变化的时候,,,,向后台请求,,,对应的列表发生变化;
    function changeXiaLa(x) {
        $(x).change(function () {
            searchKey = $('input[name = searchKey]').val();
            status = $('.status option:selected').val();
            provinceId = $('.province option:selected').val();
            company = $('.supplier option:selected').html();
            type = $('.category option:selected').val();

            if (company == '全部') {
                company = '';
            }
            ;
            page = getCommodityList(company, 1, provinceId, '', searchKey, status, type);
            getPage(page);
        });
    };
    changeXiaLa('.status');
    changeXiaLa('.supplier');
    changeXiaLa('.province');
    changeXiaLa('.category');


    // 点击编辑,,跳转到编辑的页面中去
    $(document).on('click', '.ed_intelligence', function () {
        var commondityId = $(this).parent('td').parent('tr').attr('intelligenceid');
        window.location.href = edit_intelligence + '?commondityId=' + commondityId;
    });

    //点击查看,,,,跳转到查看的页面中去
    $(document).on('click', '.look_intelligence', function () {
        var commondityId = $(this).parent('td').parent('tr').attr('intelligenceid');
        window.location.href = look_intelligence + '?commondityId=' + commondityId;
    });

    // 点击编辑,,跳转到编辑的页面中去
    $(document).on('click', '.ed_zhongYao', function () {
        var commondityId = $(this).parent('td').parent('tr').attr('intelligenceid');
        window.location.href = edit_zhongYao + '?commondityId=' + commondityId;
    });

    //点击查看,,,,跳转到查看的页面中去
    $(document).on('click', '.look_zhongYao', function () {
        var commondityId = $(this).parent('td').parent('tr').attr('intelligenceid');
        window.location.href = look_zhongYao + '?commondityId=' + commondityId;
    });


});
